import React, { useEffect, useState } from 'react';
import {
  View,
  Text,
  StyleSheet,
  FlatList,
  TouchableOpacity,
  RefreshControl
} from 'react-native';
import { LinearGradient } from 'expo-linear-gradient';
import { BlurView } from 'expo-blur';
import { Ionicons } from '@expo/vector-icons';
import { useAuth } from '../contexts/AuthContext';
import { transactionAPI } from '../utils/api';
import { theme } from '../styles/theme';

const TransactionsScreen = ({ navigation }) => {
  const { user } = useAuth();
  const [transactions, setTransactions] = useState([]);
  const [loading, setLoading] = useState(false);
  const [refreshing, setRefreshing] = useState(false);
  const [filterType, setFilterType] = useState('all'); // all, recharge, consume

  useEffect(() => {
    fetchTransactions();
  }, [filterType]);

  const fetchTransactions = async () => {
    setLoading(true);
    try {
      const params = { limit: 50 };
      if (filterType !== 'all') {
        params.type = filterType;
      }

      const response = await transactionAPI.getUserTransactions(user.id, params);
      if (response.success) {
        setTransactions(response.data.transactions);
      }
    } catch (error) {
      console.error('Fetch transactions error:', error);
    } finally {
      setLoading(false);
    }
  };

  const onRefresh = async () => {
    setRefreshing(true);
    await fetchTransactions();
    setRefreshing(false);
  };

  const renderTransaction = ({ item }) => (
    <BlurView intensity={15} tint="dark" style={styles.transactionCard}>
      <View style={styles.transactionHeader}>
        <View style={styles.transactionLeft}>
          <LinearGradient
            colors={item.type === 'recharge' ? ['#4CAF50', '#45a049'] : ['#FFC107', '#ffb300']}
            style={styles.transactionIcon}
          >
            <Ionicons
              name={item.type === 'recharge' ? 'add' : 'remove'}
              size={24}
              color="#000"
            />
          </LinearGradient>
          <View>
            <Text style={styles.transactionType}>
              {item.type === 'recharge' ? '账户充值' : '消费支出'}
            </Text>
            <Text style={styles.transactionDate}>
              {new Date(item.createdAt).toLocaleString('zh-CN', {
                year: 'numeric',
                month: '2-digit',
                day: '2-digit',
                hour: '2-digit',
                minute: '2-digit'
              })}
            </Text>
          </View>
        </View>
        <Text
          style={[
            styles.transactionAmount,
            { color: item.type === 'recharge' ? theme.colors.success : theme.colors.warning }
          ]}
        >
          {item.type === 'recharge' ? '+' : '-'}¥{parseFloat(item.amount).toFixed(2)}
        </Text>
      </View>

      {item.description && (
        <View style={styles.transactionDescription}>
          <Text style={styles.descriptionLabel}>备注：</Text>
          <Text style={styles.descriptionText}>{item.description}</Text>
        </View>
      )}

      <View style={styles.transactionFooter}>
        <Text style={styles.balanceAfter}>
          交易后余额：¥{parseFloat(item.balanceAfter).toFixed(2)}
        </Text>
      </View>
    </BlurView>
  );

  const renderEmpty = () => (
    <View style={styles.emptyContainer}>
      <Ionicons name="receipt-outline" size={64} color={theme.colors.textDim} />
      <Text style={styles.emptyText}>暂无交易记录</Text>
    </View>
  );

  return (
    <LinearGradient colors={['#000000', '#1a1a1a']} style={styles.container}>
      {/* 头部 */}
      <View style={styles.header}>
        <TouchableOpacity onPress={() => navigation.goBack()}>
          <Ionicons name="arrow-back" size={24} color={theme.colors.text} />
        </TouchableOpacity>
        <Text style={styles.headerTitle}>消费记录</Text>
        <View style={{ width: 24 }} />
      </View>

      {/* 筛选器 */}
      <View style={styles.filterContainer}>
        <TouchableOpacity
          onPress={() => setFilterType('all')}
          activeOpacity={0.8}
        >
          <BlurView
            intensity={filterType === 'all' ? 30 : 15}
            tint="dark"
            style={[
              styles.filterButton,
              filterType === 'all' && styles.filterButtonActive
            ]}
          >
            <Text
              style={[
                styles.filterText,
                filterType === 'all' && styles.filterTextActive
              ]}
            >
              全部
            </Text>
          </BlurView>
        </TouchableOpacity>

        <TouchableOpacity
          onPress={() => setFilterType('recharge')}
          activeOpacity={0.8}
        >
          <BlurView
            intensity={filterType === 'recharge' ? 30 : 15}
            tint="dark"
            style={[
              styles.filterButton,
              filterType === 'recharge' && styles.filterButtonActive
            ]}
          >
            <Text
              style={[
                styles.filterText,
                filterType === 'recharge' && styles.filterTextActive
              ]}
            >
              充值
            </Text>
          </BlurView>
        </TouchableOpacity>

        <TouchableOpacity
          onPress={() => setFilterType('consume')}
          activeOpacity={0.8}
        >
          <BlurView
            intensity={filterType === 'consume' ? 30 : 15}
            tint="dark"
            style={[
              styles.filterButton,
              filterType === 'consume' && styles.filterButtonActive
            ]}
          >
            <Text
              style={[
                styles.filterText,
                filterType === 'consume' && styles.filterTextActive
              ]}
            >
              消费
            </Text>
          </BlurView>
        </TouchableOpacity>
      </View>

      {/* 交易列表 */}
      <FlatList
        data={transactions}
        renderItem={renderTransaction}
        keyExtractor={(item) => item.id.toString()}
        contentContainerStyle={styles.listContent}
        ListEmptyComponent={renderEmpty}
        refreshControl={
          <RefreshControl refreshing={refreshing} onRefresh={onRefresh} tintColor={theme.colors.primary} />
        }
      />
    </LinearGradient>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1
  },
  header: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    paddingHorizontal: theme.spacing.lg,
    paddingTop: theme.spacing.xxl,
    paddingBottom: theme.spacing.md
  },
  headerTitle: {
    fontSize: theme.fontSizes.xlarge,
    fontWeight: 'bold',
    color: theme.colors.text
  },
  filterContainer: {
    flexDirection: 'row',
    gap: theme.spacing.sm,
    paddingHorizontal: theme.spacing.lg,
    marginBottom: theme.spacing.md
  },
  filterButton: {
    paddingHorizontal: theme.spacing.lg,
    paddingVertical: theme.spacing.sm,
    borderRadius: theme.borderRadius.round,
    borderWidth: 1,
    borderColor: theme.colors.border
  },
  filterButtonActive: {
    borderColor: theme.colors.primary
  },
  filterText: {
    fontSize: theme.fontSizes.medium,
    color: theme.colors.textSecondary
  },
  filterTextActive: {
    color: theme.colors.primary,
    fontWeight: 'bold'
  },
  listContent: {
    padding: theme.spacing.lg,
    paddingTop: 0
  },
  transactionCard: {
    borderRadius: theme.borderRadius.medium,
    padding: theme.spacing.md,
    marginBottom: theme.spacing.md,
    borderWidth: 1,
    borderColor: theme.colors.border
  },
  transactionHeader: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    marginBottom: theme.spacing.sm
  },
  transactionLeft: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: theme.spacing.md,
    flex: 1
  },
  transactionIcon: {
    width: 48,
    height: 48,
    borderRadius: theme.borderRadius.medium,
    alignItems: 'center',
    justifyContent: 'center'
  },
  transactionType: {
    fontSize: theme.fontSizes.large,
    color: theme.colors.text,
    fontWeight: '600',
    marginBottom: 4
  },
  transactionDate: {
    fontSize: theme.fontSizes.small,
    color: theme.colors.textSecondary
  },
  transactionAmount: {
    fontSize: theme.fontSizes.xlarge,
    fontWeight: 'bold'
  },
  transactionDescription: {
    flexDirection: 'row',
    marginTop: theme.spacing.sm,
    paddingTop: theme.spacing.sm,
    borderTopWidth: 1,
    borderTopColor: theme.colors.divider
  },
  descriptionLabel: {
    fontSize: theme.fontSizes.small,
    color: theme.colors.textDim,
    marginRight: theme.spacing.xs
  },
  descriptionText: {
    fontSize: theme.fontSizes.small,
    color: theme.colors.textSecondary,
    flex: 1
  },
  transactionFooter: {
    marginTop: theme.spacing.sm,
    paddingTop: theme.spacing.sm,
    borderTopWidth: 1,
    borderTopColor: theme.colors.divider
  },
  balanceAfter: {
    fontSize: theme.fontSizes.small,
    color: theme.colors.textDim
  },
  emptyContainer: {
    alignItems: 'center',
    justifyContent: 'center',
    paddingVertical: theme.spacing.xxl * 2
  },
  emptyText: {
    fontSize: theme.fontSizes.medium,
    color: theme.colors.textDim,
    marginTop: theme.spacing.md
  }
});

export default TransactionsScreen;
